<template>
  <el-form size="mini" label-width="70px" @submit.native.prevent>
    <el-form-item label-width="10px">
      <el-row>
        <el-col :span="8">
          <el-radio v-model="userTaskForm.assigneeType" label="user" @change="updateElementTask('assigneeType')">指定人员
          </el-radio>
        </el-col>
        <el-col :span="8">
          <el-radio v-model="userTaskForm.assigneeType" label="startUser" @change="updateElementTask('assigneeType')">
            发起人自己
          </el-radio>
        </el-col>
        <el-col :span="8">
          <el-radio v-model="userTaskForm.assigneeType" label="static" @change="updateElementTask('assigneeType')">自定义
          </el-radio>
        </el-col>
        <el-col :span="8">
          <el-radio v-model="userTaskForm.assigneeType" label="role" @change="updateElementTask('assigneeType')">角色
          </el-radio>
        </el-col>
        <el-col :span="8">
          <el-radio v-model="userTaskForm.assigneeType" label="dept" @change="updateElementTask('assigneeType')">部门
          </el-radio>
        </el-col>
        <el-col :span="8">
          <el-radio v-model="userTaskForm.assigneeType" label="post" @change="updateElementTask('assigneeType')">岗位
          </el-radio>
        </el-col>
      </el-row>
    </el-form-item>

    <el-divider></el-divider>

    <template v-if="userTaskForm.assigneeType === 'static'">
      <el-form-item label-width="80px" label="分配人员" style="margin-bottom: 10px;">
        <el-input v-model="userTaskForm.assignee" clearable @change="updateElementTask('assignee')"/>
      </el-form-item>
      <el-form-item label-width="80px" label="候选人员" style="margin-bottom: 10px;">
        <el-input v-model="userTaskForm.candidateUsers" clearable @change="updateElementTask('candidateUsers')"/>
      </el-form-item>
      <el-form-item label-width="80px" label="候选角色">
        <el-input v-model="userTaskForm.candidateGroups" clearable @change="updateElementTask('candidateGroups')"/>
      </el-form-item>
    </template>

    <template v-if="userTaskForm.assigneeType === 'user'">
      <el-form-item label-width="80px" label="分配人员" style="margin-bottom: 10px;">
        <input-tags v-model="userTaskForm.extAssignee"
                    append-icon="el-icon-user-solid"
                    size="mini"
                    @change="updateExtElementIdmAssignee"
                    @append-click="handleSelectAssigneeClick">
        </input-tags>
      </el-form-item>
      <el-form-item label-width="80px" label="候选人员">
        <input-tags v-model="userTaskForm.extUsers"
                    append-icon="el-icon-user-solid"
                    size="mini"
                    @change="updateExtElementAssigneeUser"
                    @append-click="handleSelectUserClick"></input-tags>
      </el-form-item>
    </template>

    <template v-if="userTaskForm.assigneeType === 'role'">
      <el-form-item label-width="80px" label="角色" style="margin-bottom: 10px;">
        <input-tags v-model="userTaskForm.extRoles"
                    append-icon="el-icon-s-custom"
                    size="mini"
                    @change="updateExtElementAssigneeRole"
                    @append-click="handleSelectRoleClick"></input-tags>
      </el-form-item>
      <el-form-item label-width="80px" label="角色范围">
        <el-radio-group v-model="userTaskForm.scope" @change="updateExtElementAssigneeScope('role')"
                        :disabled="userTaskForm.extRoles.length === 0">
          <el-radio label="Null">无限制</el-radio>
          <el-radio label="localDept">本部门</el-radio>
          <el-radio label="scopeDept">指定部门</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label-width="80px" label="指定部门" v-if="userTaskForm.scope === 'scopeDept'">
        <input-tags v-model="userTaskForm.scopeDept" :disabled="userTaskForm.extRoles.length === 0"
                    append-icon="el-icon-office-building"
                    size="mini"
                    @change="updateExtElementAssigneeScope('role')"
                    @append-click="handleSelectDeptClick"></input-tags>
      </el-form-item>
    </template>
    <template v-if="userTaskForm.assigneeType === 'dept'">
      <el-form-item label-width="80px" label="部门" style="margin-bottom: 10px;">
        <input-tags v-model="userTaskForm.extDepts"
                    append-icon="el-icon-office-building"
                    size="mini"
                    @change="updateExtElementAssigneeDept"
                    @append-click="handleSelectDeptClick"></input-tags>
      </el-form-item>

      <el-form-item label-width="80px" label="部门范围" style="margin-bottom: 10px;">
        <el-radio-group v-model="userTaskForm.scope" @change="updateExtElementAssigneeScope('dept')"
                        :disabled="userTaskForm.extDepts.length === 0">
          <el-radio label="Null">无限制</el-radio>
          <el-radio label="manager">部门负责人</el-radio>
        </el-radio-group>
      </el-form-item>
    </template>
    <template v-if="userTaskForm.assigneeType === 'post'">
      <el-form-item label-width="80px" label="岗位" style="margin-bottom: 10px;">
        <input-tags v-model="userTaskForm.extPosts"
                    append-icon="el-icon-office-building"
                    size="mini"
                    @change="updateExtElementAssigneePost"
                    @append-click="handleSelectPostClick"></input-tags>
      </el-form-item>
      <el-form-item label-width="80px" label="岗位范围">
        <el-radio-group v-model="userTaskForm.scope" @change="updateExtElementAssigneeScope('post')"
                        :disabled="userTaskForm.extPosts.length === 0">
          <el-radio label="Null">无限制</el-radio>
          <el-radio label="leader">本部门</el-radio>
        </el-radio-group>
      </el-form-item>
    </template>

    <el-divider></el-divider>

    <el-form-item label-width="120px">
      <template slot="label">
        <el-tooltip effect="dark" placement="top">
          <i class="el-icon-question"/>
          <template slot="content">
            没有审批人可进行签收、审批时的处理方案<br/>
            例如：此节点配置了候选（角色/部门/岗位），但可能角色并没有分配人员，部门/岗位下也可能没有人员的情况
          </template>
        </el-tooltip>
        <span> 审批人为空时</span>
      </template>
      <el-select v-model="userTaskForm.nullAssigneeScheme" clearable @change="updateElementTask('nullAssigneeScheme')">
        <el-option label="自动通过" value="1"></el-option>
        <el-option label="分配默认办理人" value="2"></el-option>
        <el-option label="暂停流程" value="3"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label-width="120px" v-if="userTaskForm.nullAssigneeScheme === '2'">
      <template slot="label">
        <el-tooltip effect="dark" content="分配默认办理人" placement="top">
          <i class="el-icon-question"/>
        </el-tooltip>
        <span> 默认办理人</span>
      </template>
      <input-tags v-model="userTaskForm.defaultAssignee"
                  append-icon="el-icon-user-solid"
                  size="mini"
                  @change="updateExtElementAssigneeDefaultUser"
                  @append-click="handleSelectDefaultCandidateUserClick">
      </input-tags>
    </el-form-item>
  </el-form>
</template>

<script>
import Emitter from "../../util/emitter";
import InputTags from "../../components/input-tags";

export default {
  name: "UserTaskAssignee",
  mixins: [Emitter],
  components: {
    InputTags
  },
  props: {
    id: String,
    type: String,
    businessObject: Object
  },
  inject: {
    prefix: "prefix",
  },
  data() {
    return {
      defaultTaskForm: {
        assignee: "",
        candidateUsers: "",
        candidateGroups: "",
        assigneeType: "user",
        extAssignee: [],
        extUsers: [],
        extRoles: [],
        extDepts: [],
        extPosts: [],
        defaultAssignee: [],
        scope: "Null",
        scopeDept: [],
        nullAssigneeScheme: "",
        autoSkipStrategy: "",
      },
      userTaskForm: {},
      extensionElements: []
    };
  },
  watch: {
    businessObject: {
      immediate: true,
      handler() {
        this.$nextTick(() => this.resetTaskForm());
      }
    }
  },
  created() {
    this.initParentEvent();
  },
  methods: {
    resetTaskForm() {
      this.userTaskForm = {};
      this.bpmnElement = window.bpmnInstances.bpmnElement;
      // 表单数据
      for (let key in this.defaultTaskForm) {
        let value = this.bpmnElement?.businessObject[key] || this.defaultTaskForm[key];
        this.$set(this.userTaskForm, key, value);
      }
      // 扩展人员分配情况
      this.extensionElements = this.bpmnElement.businessObject.extensionElements || window.bpmnInstances.moddle.create('bpmn:ExtensionElements', {values: []});
      let assigneeList = this.extensionElements.values.filter(element => element.$type === `${this.prefix}:Assignee`);
      let finalAssignee = {scope: "Null"};
      if (this.userTaskForm.assigneeType === 'user') {
        // 分配人员
        const assignee = assigneeList.find(assignee => assignee.type === 'assignee');
        this.userTaskForm.extAssignee = this.convertAssigneeData(assignee);
        // 候选人员
        const user = assigneeList.find(assignee => assignee.type === 'user');
        this.userTaskForm.extUsers = this.convertAssigneeData(user);
      } else if (this.userTaskForm.assigneeType === 'role') {
        const role = assigneeList.find(assignee => assignee.type === 'role');
        finalAssignee = role || finalAssignee;
        this.userTaskForm.extRoles = this.convertAssigneeData(role);
      } else if (this.userTaskForm.assigneeType === 'dept') {
        const dept = assigneeList.find(assignee => assignee.type === 'dept');
        finalAssignee = dept || finalAssignee;
        this.userTaskForm.extDepts = this.convertAssigneeData(dept);
      } else if (this.userTaskForm.assigneeType === 'post') {
        const post = assigneeList.find(assignee => assignee.type === 'post');
        finalAssignee = post || finalAssignee;
        this.userTaskForm.extPosts = this.convertAssigneeData(post);
      }
      this.userTaskForm.scope = finalAssignee.scope || this.defaultTaskForm.scope;
      this.userTaskForm.scopeDept = this.convertAssigneeScopeData(finalAssignee) || this.defaultTaskForm.scopeDept;
      // 默认分配人
      const defAssignee = assigneeList.find(assignee => assignee.type === 'defAssignee');
      this.userTaskForm.defaultAssignee = this.convertAssigneeData(defAssignee);
    },
    convertAssigneeData(data) {
      let result = [];
      if (data && data.value && data.text) {
        let ids = data.value.split(",");
        let names = data.text.split(",");
        for (let i = 0; i < ids.length; i++) {
          result.push({label: names[i], value: ids[i]});
        }
      }
      return result;
    },
    convertAssigneeScopeData(data) {
      let result = [];
      if (data && data.scopeValue && data.scopeText) {
        let ids = data.scopeValue.split(",");
        let names = data.scopeText.split(",");
        for (let i = 0; i < ids.length; i++) {
          result.push({label: names[i], value: ids[i]});
        }
      }
      return result;
    },
    updateElementTask(key) {
      const taskAttr = Object.create(null);
      taskAttr[key] = this.userTaskForm[key] || null;

      // 处理不同人员类型的默认值
      if (key === 'assigneeType') {
        if (this.userTaskForm[key] === 'startUser') {
          taskAttr['assignee'] = '${initiator}';
          taskAttr["candidateUsers"] = null;
          taskAttr["candidateGroups"] = null;
        } else if (this.userTaskForm[key] === 'static') {
          taskAttr['assignee'] = null;
        } else {
          taskAttr["assignee"] = null;
          taskAttr["candidateUsers"] = null;
          taskAttr["candidateGroups"] = null;
        }
        // 判断开启了多实例，则将分配人设置为从变量获取
        if (this.businessObject.loopCharacteristics) {
          taskAttr["assignee"] = '${assignee}';
        }
        this.deleteAllExtElementAssignee();
      }
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, taskAttr);
    },
    /**
     * 更新Assignee--------------------------------------------------
     */
    updateExtElementIdmAssignee(users) {
      this.deleteExtElementAssignee('assignee');
      this.updateExtElementAssignee('assignee', users);
    },
    updateExtElementAssigneeUser(data) {
      this.deleteExtElementAssignee('user');
      this.updateExtElementAssignee('user', data);
    },
    updateExtElementAssigneeRole(data) {
      this.deleteExtElementAssignee('role');
      this.updateExtElementAssignee('role', data);
    },
    updateExtElementAssigneeDept(data) {
      this.deleteExtElementAssignee('dept');
      this.updateExtElementAssignee('dept', data);
    },
    updateExtElementAssigneePost(data) {
      this.deleteExtElementAssignee('post');
      this.updateExtElementAssignee('post', data);
    },
    updateExtElementAssigneeDefaultUser(data) {
      this.deleteExtElementAssignee('defAssignee');
      this.updateExtElementAssignee('defAssignee', data);
    },
    updateExtElementAssigneeScope(type) {
      let assigneeList = this.extensionElements.values.filter(element => element.$type === `${this.prefix}:Assignee`);
      const assignee = assigneeList.find(assignee => assignee.type === type);
      this.deleteExtElementAssignee(type);
      // 范围
      assignee.scope = this.userTaskForm.scope === "Null" ? null : this.userTaskForm.scope;
      let text = [];
      let value = [];
      (this.userTaskForm.scopeDept || []).forEach(item => {
        text.push(item.label);
        value.push(item.value);
      });
      assignee.scopeText = text.join(",");
      assignee.scopeValue = value.join(",");

      this.extensionElements.values.push(assignee);
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {extensionElements: this.extensionElements});
    },
    updateExtElementAssignee(type, data) {
      if (data && Array.isArray(data)) {
        if (data.length === 0) {
          this.userTaskForm.scope = "Null";
        } else {

          // 范围控制，角色、部门、岗位才支持范围控制
          let scope = null;
          if (['role', 'dept', 'post'].includes(type)) {
            scope = this.userTaskForm.scope === "Null" ? null : this.userTaskForm.scope;
          }
          // 更新
          let text = [];
          let value = [];
          (data || []).forEach(item => {
            text.push(item.label);
            value.push(item.value);
          });
          let assignee = window.bpmnInstances.moddle.create(`${this.prefix}:Assignee`, {
            type: type,
            text: text.join(","),
            value: value.join(","),
            scope: scope
          });
          this.extensionElements.values.push(assignee);
          window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {extensionElements: this.extensionElements});
        }
      }
    },
    deleteExtElementAssignee(type) {
      let elements = this.extensionElements.values;
      let length = elements.length;
      while (length--) {
        if (elements[length].$type === `${this.prefix}:Assignee` && elements[length].type === type) {
          elements.splice(length, 1);
        }
      }
    },
    deleteAllExtElementAssignee() {
      let elements = this.extensionElements.values;
      let length = elements.length;
      while (length--) {
        // 跳过默认办理人
        if (elements[length].type === 'defAssignee') {
          continue;
        }
        // 删除其他所有
        if (elements[length].$type === `${this.prefix}:Assignee`) {
          elements.splice(length, 1);
        }
      }
      window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {extensionElements: this.extensionElements});
    },

    // 触发选择事件----------------------------------------------------------------------
    handleSelectUserClick(tagsData, resolve) {
      this.dispatch("pu-bpmn-design", "user-task-select-user", {tagsData, resolve})
    },
    handleSelectRoleClick(tagsData, resolve) {
      this.dispatch("pu-bpmn-design", "user-task-select-role", {tagsData, resolve})
    },
    handleSelectDeptClick(tagsData, resolve) {
      this.dispatch("pu-bpmn-design", "user-task-select-dept", {tagsData, resolve})
    },
    handleSelectPostClick(tagsData, resolve) {
      this.dispatch("pu-bpmn-design", "user-task-select-post", {tagsData, resolve})
    },
    handleSelectAssigneeClick(tagsData, resolve) {
      this.dispatch("pu-bpmn-design", "user-task-select-assignee", {tagsData, resolve})
    },
    handleSelectDefaultCandidateUserClick(tagsData, resolve) {
      this.dispatch("pu-bpmn-design", "user-task-select-assignee", {tagsData, resolve})
    },
    // 父组件事件
    initParentEvent() {
      this.$on("updateIdmAssignee", (users = []) => {
        if (Array.isArray(users)) {
          if (users.length > 0) {
            users = [users[0]];
          }
        } else {
          users = [users];
        }
        this.updateExtElementIdmAssignee(users);
      });
      this.$on("updateIdmUser", (users) => {
        this.updateExtElementAssigneeUser(users);
      });
      this.$on("updateIdmRole", (roles) => {
        this.updateExtElementAssigneeRole(roles);
      });
      this.$on("updateIdmDept", (depts) => {
        this.updateExtElementAssigneeDept(depts);
      });
      this.$on("updateIdmPost", (posts) => {
        this.updateExtElementAssigneePost(posts);
      });
    }
  },
  beforeDestroy() {
    this.bpmnElement = null;
  }
}
</script>

<style>


</style>
